package com.zhangxiaofanfan.service.download.impl;

import com.zhangxiaofanfan.service.download.DownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

/**
 * 下载服务实现类
 *
 * @author zhangxiaofanfan
 * @date 2024-11-04 11:06:59
 */
@Slf4j
@Service
public class DownloadServiceImpl implements DownloadService {

    @Override
    public boolean download(String source, String target) {
        log.info("目标路径为: {}, 下载使用的临时文件夹为: {}", source, target);
        // 1. 重置下载所使用的文件夹
        File targetFile = new File(target);
        if (targetFile.exists()) {
            throw new RuntimeException(String.format("目标文件夹存在[%s], 无法在此文件夹下载文件, 请重新确认下载地址", target));
        }
        if (!targetFile.mkdirs()) {
            throw new RuntimeException(String.format("创建目标文件夹[%s]失败!", target));
        }
        String targetFilePath = String.join(File.separator, target, source.substring(source.lastIndexOf('/')));
        // 2. 下载文件
        try (FileOutputStream outputStream = new FileOutputStream(targetFilePath)) {
            URL url = URI.create(source).toURL();
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            byte[] buffer = new byte[1024 * 1024];
            int byteRead;
            while ((byteRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, byteRead);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}
